import React, { useState, useEffect } from "react";
import { useMount } from "utils";

const test = () => {
  let num = 0;
  const effect = () => {
    num += 1;
    const message = `现在的num值：${num}`;
    return function unmount() {
      console.log(message);
    };
  };
  return effect;
};
const add = test();
const unmount = add();
add();
add();
unmount(); //打印结果“现在的num值：1”

export const Test = () => {
  const [num, setNum] = useState(0);
  const add = () => setNum(num + 1);
  useMount(() => {
    //只在页面加载的时候取得num的值，后续不论页面执行了什么操作都不会改变num的取值
    setInterval(() => {
      console.log("interval", num);
    }, 1000);
  });
  useEffect(() => {
    //只在页面加载的时候取得num的值，后续不论页面执行了什么操作都不会改变num的取值
    //只需要在依赖项中添加num就能获取增加后的结果
    return () => {
      console.log("卸载", num);
    };
  }, []);

  return (
    <div>
      <button onClick={add}>+1</button>
    </div>
  );
};
